package com.atguigu.lease.web.app.custom.Interceptor;

import com.atguigu.lease.common.context.LoginAppUser;
import com.atguigu.lease.common.context.LoginAppUserContext;
import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.common.utils.JwtUtilApp;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @BelongsProject: lease
 * @BelongsPackage: com.atguigu.lease.web.admin.custom.Interceptor
 * @Author: jiangyi
 * @CreateTime: 2025-08-22  16:26
 * @Description: TODO
 * @Version: 1.0
 */

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 访问控制器之前执行验证服务
        // 从请求头中获取 access_token
        String token = request.getHeader("access_token");
        Claims claims = JwtUtilApp.parseToken(token);
        String phone = claims.get("phone", String.class);
        LoginAppUserContext.setLoginAppUser(new LoginAppUser(phone));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求处理完成后，清除登录用户信息
        LoginUserContext.clear();
    }
}
